package com.higgins.eventtracking.client;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.higgins.eventtracking.client.dto.DynamicTypeDTO;
import com.higgins.eventtracking.client.dto.TrackingEventDTO;
import com.higgins.eventtracking.shared.FieldVerifier;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class EventTracking implements EntryPoint {
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	/**
	 * Create a remote service proxy to talk to the server-side Greeting service.
	 */
	private final EventTrackingServiceAsync greetingService = GWT
			.create(EventTrackingService.class);
	private final FinanceTrackingServiceAsync financeTrackingService = GWT
				.create(FinanceTrackingService.class);

	
	private final ListBox eventTypeList = new ListBox();

	private final Label distanceLabel = new Label("Distance: ");
	private final Label minutesLabel = new Label("Minutes: ");
	private final Label secondsLabel = new Label("Seconds: ");
	private final Label weightLabel = new Label("Weight: ");
	private final Label repsLabel = new Label("Reps: ");
	private final Label error = new Label("");

	private final TextBox distanceField = new TextBox();
	private final TextBox minutesField = new TextBox();
	private final TextBox secondsField = new TextBox();
	private final TextBox weightField = new TextBox();
	private final TextBox repsField = new TextBox();

	private final Button sendButton = new Button("Add");

	private final TextBox nameField = new TextBox();
	private final Label errorLabel = new Label();
	private final DialogBox dialogBox = new DialogBox();
	private final Button closeButton = new Button("Close");
	private final Label textToServerLabel = new Label();
	private final HTML serverResponseLabel = new HTML();

	
	/**
	 * This is the entry point method.
	 */

	private void loadExerciseTypesList()	{
		eventTypeList.addItem("------");
		try {
			financeTrackingService.retrieveDynamicTypes("ExerciseType", new AsyncCallback<List<DynamicTypeDTO>>()  {

				@Override
				public void onFailure(Throwable caught) {
					eventTypeList.addItem("Failed!!!");

				}

				@Override
				public void onSuccess(List<DynamicTypeDTO> result) {
					for (DynamicTypeDTO dto:result)	{
						eventTypeList.addItem(dto.getDynamicType());
					}
					
				} });
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityAccessDeniedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
//		eventTypeList.addItem("Stretching");
//		eventTypeList.addItem("Squats");		
//		eventTypeList.addItem("Pull-overs");		
//		eventTypeList.addItem("Barbell Rows");		
//		eventTypeList.addItem("Deadlifts");		
//		eventTypeList.addItem("Bench Press");		
//		eventTypeList.addItem("Abs");		
//		eventTypeList.addItem("Obliques");		
//		eventTypeList.addItem("Ab Twists");		
//		eventTypeList.addItem("Lower Back");		
//		eventTypeList.addItem("Delts Butterfly");		
//		eventTypeList.addItem("Delts Vertical");		
//		eventTypeList.addItem("Bicep Curls");		
//		eventTypeList.addItem("Triceps Exts");		
//		eventTypeList.addItem("Upper Back");		
//		eventTypeList.addItem("Leg Extension");
//		eventTypeList.addItem("Leg Curls");
//		eventTypeList.addItem("Walking");
//		eventTypeList.addItem("Cycling");
//		eventTypeList.addItem("Running");
//		eventTypeList.addItem("Swimming");		

	}
	
	public void onModuleLoad() {
		loadExerciseTypesList();
		
		// We can add style names to widgets
		sendButton.addStyleName("sendButton");

		RootPanel.get().add(eventTypeList);
		RootPanel.get().add(sendButton);
		

		class MyHandler implements ClickHandler, ChangeHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				sendTrackingEventToServer();
			}


			/**
			 * Send the name from the nameField to the server and wait for a response.
			 */
			private void sendTrackingEventToServer() {
				// First, we validate the input.
				errorLabel.setText("");
				Double distance = 0.0;
				Integer minutes = 0;
				Integer seconds = 0;
				Double weight = 0.0;
				Integer reps = 0;
				
				distance = new Double(distanceField.getText());
				minutes = new Integer(minutesField.getText());
				seconds = new Integer(secondsField.getText());
				weight = new Double(weightField.getText());
				reps = new Integer(repsField.getText());

				
				TrackingEventDTO dto = new TrackingEventDTO();
				dto.setEventType(eventTypeList.getItemText(eventTypeList.getSelectedIndex()));
				dto.setTimeStamp(new Date());
				dto.setDistance(distance);
				dto.setMinutes(minutes);
				dto.setSeconds(seconds);
				dto.setWeight(weight);
				dto.setReps(reps);
				
				sendButton.setEnabled(false);
				greetingService.insertTrackingEvent(dto,
						new AsyncCallback<String>() {
							public void onFailure(Throwable caught) {
								sendButton.setEnabled(true);
								error.setText("FAILURE");
							}

							public void onSuccess(String result) {
								sendButton.setEnabled(true);
								error.setText("SUCCESS");
							}
						});
			}
	
			private void setFieldsToBlank()	{
				distanceField.setText("");
				minutesField.setText("");
				secondsField.setText("");
				weightField.setText("");
				repsField.setText("");
				error.setText("");
			}
			private void setFieldsToZero()	{
				distanceField.setText("0.0");
				minutesField.setText("0");
				secondsField.setText("0");
				weightField.setText("0.0");
				repsField.setText("0");
				error.setText("");
			}
			private void blankCardioFields()	{
				Iterator<Widget> iterator = RootPanel.get().iterator();
				while (iterator.hasNext())	{
					Widget widget = iterator.next();
					RootPanel.get().remove(widget);
				}
				
				RootPanel.get().remove(distanceLabel);
				RootPanel.get().remove(minutesLabel);
				RootPanel.get().remove(secondsLabel);
				RootPanel.get().remove(weightLabel); 
				RootPanel.get().remove(repsLabel); 
				
				RootPanel.get().add(eventTypeList);
				RootPanel.get().add(sendButton);
				RootPanel.get().add(error);
				setFieldsToBlank();
				
			}			
			private void displayCardioFields()	{
				Iterator<Widget> iterator = RootPanel.get().iterator();
				while (iterator.hasNext())	{
					Widget widget = iterator.next();
					RootPanel.get().remove(widget);
				}
				
				RootPanel.get().remove(distanceLabel);
				RootPanel.get().remove(minutesLabel);
				RootPanel.get().remove(secondsLabel);
				RootPanel.get().remove(weightLabel); 
				RootPanel.get().remove(repsLabel); 
				
				RootPanel.get().add(eventTypeList);
				RootPanel.get().add(distanceLabel);
				RootPanel.get().add(distanceField);
				RootPanel.get().add(minutesLabel);
				RootPanel.get().add(minutesField);
				RootPanel.get().add(secondsLabel);
				RootPanel.get().add(secondsField);
				RootPanel.get().add(sendButton);
				RootPanel.get().add(error);
				setFieldsToBlank();
			}
			private void displayAnabolicFields()	{
				Iterator<Widget> iterator = RootPanel.get().iterator();
				while (iterator.hasNext())	{
					Widget widget = iterator.next();
					RootPanel.get().remove(widget);
				}
				RootPanel.get().remove(distanceLabel);
				RootPanel.get().remove(minutesLabel);
				RootPanel.get().remove(secondsLabel);
				RootPanel.get().remove(weightLabel); 
				RootPanel.get().remove(repsLabel); 
				
				RootPanel.get().add(eventTypeList);
				RootPanel.get().add(weightLabel);
				RootPanel.get().add(weightField);
				RootPanel.get().add(repsLabel);
				RootPanel.get().add(repsField);
				RootPanel.get().add(sendButton);
				RootPanel.get().add(error);
				
				setFieldsToBlank();
			}

			@Override
			public void onChange(ChangeEvent event) {
				if (eventTypeList.getItemText(eventTypeList.getSelectedIndex()).equals("Stretching")) 	{
					blankCardioFields();
				} else if (
					eventTypeList.getItemText(eventTypeList.getSelectedIndex()).equals("Walking") ||
					eventTypeList.getItemText(eventTypeList.getSelectedIndex()).equals("Cycling") || 
					eventTypeList.getItemText(eventTypeList.getSelectedIndex()).equals("Running") || 
					eventTypeList.getItemText(eventTypeList.getSelectedIndex()).equals("Swimming"))	{
					displayCardioFields();
				} else {
					displayAnabolicFields();
				}
				
				// RETRIEVE LAST RECORD HERE!!!! THEN SET THE TEXT BOXES
				greetingService.retrieveTrackingEvent(eventTypeList.getItemText(eventTypeList.getSelectedIndex()),
						new AsyncCallback<TrackingEventDTO>() {
							public void onFailure(Throwable caught) {
								setFieldsToZero();
							}

							@SuppressWarnings("unused")
							public void onSuccess(TrackingEventDTO result) {
								setFieldsToZero();
								
								if (result!=null)	{
									distanceField.setText(result.getDistance().toString());
									minutesField.setText(result.getMinutes().toString());
									secondsField.setText(result.getSeconds().toString());
									weightField.setText(result.getWeight().toString());
									repsField.setText(result.getReps().toString());
								}	
							}
						});
				
				
			}
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		sendButton.addClickHandler(handler);
		eventTypeList.addChangeHandler(handler);
	}
}
